package com.keepers.repair.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.location.Location;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.widget.TextView;

import com.keepers.repair.R;
import com.keepers.repair.helper.SpHelper;
import com.keepers.repair.model.UserModel;
import com.keepers.repair.net.Call;
import com.keepers.repair.net.DataLoader;
import com.keepers.repair.net.LogUtil;
import com.keepers.repair.utils.AlertToast;
import com.keepers.repair.utils.DefaultUtils;
import com.keepers.repair.utils.LocationUtils;
import com.keepers.repair.utils.UtilsKt;
import com.keepers.repair.view.MovieRecorderView;
import com.keepers.repair.view.TitleBar;
import com.werb.permissionschecker.PermissionChecker;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;

/**
 * auth aboom
 * date 2018/11/29
 */
public class SOSMovieActivity extends BaseActivity {

    private static final String[] PERMISSIONS = {Manifest.permission.ACCESS_FINE_LOCATION};

    private UserModel         loginUserInfo;
    private PermissionChecker permissionChecker;
    private Location          location;
    private MovieRecorderView movieRecorderView;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sos_movie);
        loginUserInfo = SpHelper.getLoginUserInfo();
        TitleBar titleBar = f(R.id.title_bar);
        TextView textView = titleBar.initializeHeader("报警视频录制中");
        textView.setTextColor(ActivityCompat.getColor(this, R.color.red));
        movieRecorderView = f(R.id.sos_movie);
        f(R.id.cancel_shoot_button).setOnClickListener(v -> {
            movieRecorderView.stop();
            rxHelper.pend(Observable.timer(1000, TimeUnit.MILLISECONDS, AndroidSchedulers.mainThread())
                    .subscribe(aLong -> finish()));
        });
        startRecord(100, movieRecorderView);
        permissionChecker = new PermissionChecker(this);
        if (permissionChecker.isLackPermissions(PERMISSIONS)) {
            permissionChecker.requestPermissions();
        } else {
            location = LocationUtils.getInstance(this).showLocation();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode == PermissionChecker.PERMISSION_REQUEST_CODE && permissionChecker.hasAllPermissionsGranted(grantResults)) {
            location = LocationUtils.getInstance(this).showLocation();
        } else {
            AlertToast.show("请开启定位权限权限！");
        }
    }

    private void startRecord(long time, MovieRecorderView movieRecorderView) {
        rxHelper.pend(Observable.timer(time, TimeUnit.MILLISECONDS, AndroidSchedulers.mainThread())
                .subscribe(aLong -> movieRecorderView.record(() -> {
                    uploadMovie(movieRecorderView);
                    startRecord(1500, movieRecorderView);
                })));
    }

    @SuppressLint("SimpleDateFormat")
    private void uploadMovie(MovieRecorderView movieRecorderView) {
        if (UtilsKt.isNetworkConnected()) {

//            List<RepairModel> repairModels = SpHelper.getRepairModels();
//            if (CollectionUtil.isNotEmpty(repairModels)) {
//                repairModels = Observable.fromIterable(repairModels)
//                        .filter(repairModel -> repairModel.RIsState == 1)
//                        .toList().blockingGet();
//            }
//            Date parse = null;
//            RepairModel repair = null;
//            if (CollectionUtil.isNotEmpty(repairModels)) {
//                for (RepairModel repairModel : repairModels) {
//                    try {
//                        Date date = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").parse(repairModel.SubmitTime);
//                        if (parse == null) {
//                            parse = date;
//                            repair = repairModel;
//                        }
//                        if (parse != null) {
//                            boolean before = parse.before(date);
//                            if (before) {
//                                parse = date;
//                                repair = repairModel;
//                            }
//                        }
//                    } catch (ParseException e) {
//                        e.printStackTrace();
//                    }
//                }
//            }
            String filePath = movieRecorderView.getmVecordFile().toString();
            LogUtil.e("sos filePath = " + filePath);
            String fileName = filePath.substring(filePath.lastIndexOf("/") + 1);
            String encodeBase64File = UtilsKt.encodeBase64File(filePath);
            String userGid = loginUserInfo.Gid;
            String treeGid = loginUserInfo.GroupGid;
            String taskId = "";
            String taskPId = "";
            String devicePhone = "DevicePhone";
            String placeGid = "";
            String longitude = location != null ? String.valueOf(location.getLongitude()) : "";
            String latitude = location != null ? String.valueOf(location.getLatitude()) : "";
            String createTime = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(new Date());
            LogUtil.e("fileName = " + fileName + "  userGid = " + userGid + " TreeGid = " + treeGid + "" + " longitude = " + longitude + " latitude = " + latitude + " DataTime = " + createTime);

            UtilsKt.safelyTask(() -> AlertToast.show("报警视频上传..."));
            rxHelper.pend(DataLoader.saveSOSInfor(encodeBase64File, fileName, userGid, treeGid, taskId, taskPId, placeGid, devicePhone, longitude, latitude, createTime, new Call<Boolean>() {
                @Override
                public void call(Boolean aBoolean) {
                    if (DefaultUtils.value(aBoolean)) {
                        AlertToast.show("报警视频上传成功...");
                    } else {
                        AlertToast.show("报警视频上传失败...");
                    }
                }
            }));
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        movieRecorderView.stop();
        LocationUtils.getInstance(this).removeLocationUpdatesListener();
    }
}
